import { Injectable } from '@nestjs/common';
import axios, { AxiosError } from 'axios';
import * as fs from 'fs/promises';
import * as path from 'path';

interface ZhipuResponse {
  choices: [
    {
      message: {
        content: string;
      };
    },
  ];
}

@Injectable()
export class AppService {
  private readonly zhipuApiKey: string;
  private readonly zhipuApiUrl =
    'https://open.bigmodel.cn/api/paas/v4/chat/completions';
  private readonly uploadDir = path.join(process.cwd(), 'uploads');

  constructor() {
    this.zhipuApiKey = process.env.ZHIPU_API_KEY as string;
    if (!this.zhipuApiKey) {
      throw new Error('ZHIPU_API_KEY 环境变量未设置');
    }

    void this.ensureUploadDir().catch((error) => {
      console.error('创建上传目录失败:', error);
      throw error;
    });
  }

  private async ensureUploadDir() {
    try {
      await fs.access(this.uploadDir);
    } catch {
      await fs.mkdir(this.uploadDir, { recursive: true });
    }
  }

  async recognizeImage(imageData: string): Promise<{ result: string }> {
    try {
      let imgBase64 = '';
      if (imageData.startsWith('http')) {
        imgBase64 = await this.downloadImageToBase64(imageData);
      } else {
        imgBase64 = imageData.split(',')[1];

        // 保存图片到本地
        const filename = `drawing_${Date.now()}.jpg`;
        const filepath = path.join(this.uploadDir, filename);
        try {
          await fs.writeFile(filepath, Buffer.from(imgBase64, 'base64'));

          // 验证保存的图片
          const stats = await fs.stat(filepath);

          if (stats.size === 0) {
            console.error('警告：保存的图片大小为0');
          }
        } catch (saveError) {
          console.error('保存图片时出错:', saveError);
        }
      }

      const response = await axios.post<ZhipuResponse>(
        this.zhipuApiUrl,
        {
          model: 'glm-4v-flash',
          messages: [
            {
              role: 'user',
              content: [
                {
                  type: 'image_url',
                  image_url: {
                    url: `data:image/jpeg;base64,${imgBase64}`,
                  },
                },
                {
                  type: 'text',
                  text: '这是一个你画我猜的游戏。请猜测这幅手绘图画中画的是什么。请用简短的一句话回答，不要太长的描述。如果看不出画的是什么，就抽象的描述。',
                },
              ],
            },
          ],
        },
        {
          headers: {
            Authorization: `Bearer ${this.zhipuApiKey}`,
            'Content-Type': 'application/json',
          },
          timeout: 30000,
        },
      );

      return { result: response.data.choices[0].message.content };
    } catch (error) {
      console.error('图像识别请求详细错误:', error);
      if (axios.isAxiosError(error)) {
        const axiosError = error as AxiosError;
        const errorMessage = axiosError.response?.data
          ? JSON.stringify(axiosError.response.data)
          : axiosError.message;
        console.error('API错误详情:', errorMessage);
        console.error('错误状态码:', axiosError.response?.status);
        console.error('错误响应头:', axiosError.response?.headers);

        if (axiosError.code === 'ECONNABORTED') {
          return { result: '请求超时，请重试' };
        }
        return { result: `识别请求失败: ${errorMessage}` };
      }
      return { result: '图像识别发生未知错误，请稍后重试' };
    }
  }

  private async downloadImageToBase64(url: string): Promise<string> {
    try {
      const response = await axios.get<Buffer>(url, {
        responseType: 'arraybuffer',
        timeout: 5000,
      });

      return Buffer.from(response.data).toString('base64');
    } catch (error) {
      console.error('下载图片失败:', error);
      throw new Error('下载图片失败');
    }
  }
}
